<?php
	/**
	 * File class represents an existing file in the filesystem.
	 * @author IMP
	 */
	
	class File {
		protected $filePath;
		
		public function __construct($path2file, $create = false){
			if(is_file($path2file) || $create){
				if($create && !is_file($path2file)) touch($path2file);
				$this->filePath = $path2file;
			}else{
				throw new FileNotFoundException($path2file);
			}
		}
		
		public function openStream($mode = 'w+'){
			return fopen($this->getAbsolutePath(), $mode);
		}
		
		public function __toString(){
			return $this->getAbsolutePath();
		}
		
		public function getPath(){
			return $this->filePath;
		}
		
		public function getAbsolutePath(){
			return realpath($this->getPath());
		}
		
		public function getAbsoluteFile(){
			 return new self($this->getAbsolutePath());
		}
		
		public final function hasReadPermission(){
			return posix_access($this->getAbsolutePath(), POSIX_R_OK);
		}
		
		public final function hasWritePermission(){
			return posix_access($this->getAbsolutePath(), POSIX_F_OK);
		}
		
		public final function hasExecutePermission(){
			return posix_access($this->getAbsolutePath(), POSIX_X_OK);
		}
		
		public function getSize(){
			return filesize($this->getAbsolutePath());
		}
		
		public function getModificationTime(){
			return filemtime($this->getAbsolutePath());
		}
		
		public final function read(){
			if($this->hasReadPermission()){
				return file_get_contents($this->getAbsolutePath());
			}else{
				throw new FilePermissionException(true, false, false);
			}
		}
		
		public final function readLines($lineBreak = PHP_EOL){
			$content = $this->read();
			return explode($lineBreak, $content);
		}
		
		public final function write($data){
			if($this->hasWritePermission()){
				return file_put_contents($this->getAbsolutePath(), $data);
			}else{
				throw new FilePermissionException(false, true, false);
			}
		}
		
		public final function append($data){
			if($this->hasWritePermission()){
				return file_put_contents($this->getAbsolutePath(), $data, FILE_APPEND);
			}else{
				throw new FilePermissionException(false, true, false);
			}
		}
		
		public function getExtension(){
			$v = explode('.', $this->filePath);
			return strtolower(end($v));
		}
		
		public function getMIMEType(){
			if(version_compare(PHP_VERSION, '5.3.0', '>=')){
				$r = finfo_open(FILEINFO_MIME_TYPE);
				$m = finfo_file($r, $this->getAbsolutePath());
				finfo_close($r);
				
				return $m;
			}else{
				return mime_content_type($this->getAbsolutePath());
			}
		}
		
		public function getParent(){
			return new Dir(dirname($this->getAbsolutePath()));
		}
		
		public static function exists($path2file){
			return is_file($path2file);
		}
	}
?>